package cn.yitun.chat.yitunserverimcore.general.main.push.auth;

import cn.yitun.chat.yituncommonmessage.client.Client;
import cn.yitun.chat.yituncommonmessage.impl.HeadImpl;
import cn.yitun.chat.yituncommonmessage.push.PushMessage;
import cn.yitun.chat.yitunnetsession.session.SocketSession;
import cn.yitun.chat.yitunservercommonlib.constant.ActionTypeConstant;
import cn.yitun.chat.yitunservercommonlib.enums.control.push.auth.AuthPushMethodEnum;
import cn.yitun.chat.yitunservercommonlib.util.codec.IdGen;
import cn.yitun.chat.yitunserverimcore.bridge.net.WriteHandler;
import cn.yitun.chat.yitunserverimcore.general.common.util.PushMessageBuild;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class AuthPush {

	@Resource
	WriteHandler writeHandler;
	//1.1.000
	final String action = ActionTypeConstant.ACCOUNT_ACTION_PUSH;

	/**
	 * 推送验证信息
	 * @param key
	 * @param currentOffline
	 * @param token
	 */
	public void pushAuthMsg(Long key, boolean currentOffline, String token) {
		HeadImpl head = new HeadImpl();
		head.setAction(action);
		head.setMethod(AuthPushMethodEnum.SEND_AUTH_RESULT.getMethod());
		head.setTimestamp(System.currentTimeMillis());
		head.setKey(key);

		PushMessage message = new PushMessage();
		message.setHead(head);
		message.bodyPut("currentOffline", currentOffline);
		message.bodyPut("token", token);
		writeHandler.push(key, message);
	}

	/**
	 * 推送其他客户端登陆信息
	 *
	 * @param set
	 * @param offline
	 * @param client
	 */
	public void pushOtherOnline(Set<SocketSession> set, Client client, boolean offline) {

		String method = AuthPushMethodEnum.OTHER_ONLINE.getMethod();
		Long key = IdGen.getNumber();
		PushMessage message = PushMessageBuild.build(key, action, method);
		message.bodyPut("client", client);
		message.bodyPut("offline", offline);// 当前设备是否下线：true：下线 false:不用下线
		for (SocketSession ss : set) {
			try {
				ss.write(message);
			} catch (Exception e) {
			}
		}

		for (SocketSession ss : set) {
			try {
				ss.close();
			} catch (Exception e) {
			}
		}
	}



}
